package com.whut.service.impl;

import com.whut.entity.UserLogin;
import com.whut.mapper.UserLoginMapper;
import com.whut.service.IUserLoginService;
import com.whut.util.RandomCodeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class UserLoginService implements IUserLoginService {
    @Autowired
    private UserLoginMapper userMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public UserLogin login(String username, String password) {
        UserLogin user = userMapper.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public boolean register(UserLogin user) {
        try {
            return userMapper.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String verifyEmail(String email) {
        UserLogin user1 = userMapper.findByEmail(email);
        if (user1 == null) {
            return "用户不存在";
        }
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 设置邮件主题
            mailMessage.setSubject("测试邮箱验证码");
            // 工具类生成随机六位验证码
            String code = RandomCodeUtils.get6BitRandom();
            // 设置邮件内容
            mailMessage.setText("您收到的验证码是:"+code);
            // 设置收发人
            mailMessage.setFrom(from);
            mailMessage.setTo(email);
            // 发送
            mailSender.send(mailMessage);
            return code;
        } catch (MailException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public boolean updatePassword(UserLogin user) {
        try {
            UserLogin existingUser = userMapper.findByEmail(user.getEmail());
            if (existingUser == null) {
                throw new IllegalArgumentException("用户不存在");
            }
            existingUser.setPassword(user.getPassword());
            return userMapper.updatePassword(existingUser);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



}
